package com.md.mainpage.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.md.mainpage.R
import com.md.mainpage.databinding.AdpterLeftCategoryBinding
import com.md.network.api.Category

class MainCategoryLeftAdapter(mContext: Context, private var mData:List<Category>, mCallback: SelectedCategoryCallback):RecyclerView.Adapter<MainCategoryLeftAdapter.LeftCategoryViewHolder>() {

    private var mContext:Context = mContext
    private var curSelPos=0
    private var callback= mCallback
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LeftCategoryViewHolder {
        var view = LayoutInflater.from(mContext).inflate(R.layout.adpter_left_category,parent,false)
       return LeftCategoryViewHolder(view)
    }

    override fun getItemCount(): Int {
       return mData.size
    }

    override fun onBindViewHolder(holder: LeftCategoryViewHolder, position: Int) {
       var category = mData[position]
        var colorId = if (category.isSel)mContext.resources.getColor( R.color.maincolor_white) else mContext.resources.getColor(R.color.maincolor_F4F5F6)
        holder.ctlRoot?.let {
            it.setBackgroundColor(colorId)
            it.setOnClickListener {
                curSelPos = position
                refreshItemSelStatue(position)
                notifyDataSetChanged()
                callback.selectedCategory(category)
            }
        }
        holder.tvTitle?.let {
            it.text = category.name
            if (position==curSelPos)
                it.setTextColor(mContext.resources.getColor(R.color.maincolor_12C286))
            else
                it.setTextColor(mContext.resources.getColor(R.color.maincolor_595959))
        }
    }

    fun refreshItemSelStatue(pos:Int){
        for(index in mData.indices){
            mData[index].isSel = index==pos
        }
    }


    public fun setData( mData:List<Category>){
        this.mData = mData
        notifyDataSetChanged()
    }

    class LeftCategoryViewHolder : RecyclerView.ViewHolder{
        var tvTitle:TextView?= null
        var ctlRoot:ConstraintLayout?=null

        constructor(itemView: View):super(itemView){
            tvTitle = itemView.findViewById(R.id.tvCategory)
            ctlRoot = itemView.findViewById(R.id.ctlLeftRoot)
        }

    }

    interface SelectedCategoryCallback{
        fun selectedCategory(category: Category)
    }
}